'''
Created on 05/04/2013

@author: tsantana
'''

import thilux_util
import thilux_security
import thilux_session

import logging

from google.appengine.ext import webapp
# from google.appengine.ext.webapp import util
from thilux_models import User, Role, Department, Position

from datetime import datetime


_STATUS_ACTIVE = 1
_STATUS_BLOCKED = 2
_STATUS_EXPIRED = 3
_STATUS_DELETED = 4


def get_managers():
    managers=User.gql('WHERE role = :1', Role.get_by_key_name('Department Manager'))
    
    return managers

class GetTest(webapp.RequestHandler):
    def get(self, q):
        html_page = ('GET_TEST_PAGE')
        
        thilux_util.render_page(self.response, html_page)
        
class AddEmployee(webapp.RequestHandler):
    def get(self):
        html_page=('ADD_EMPLOYEE_PAGE')
        
        data={}
        managers=get_managers()
        positions=Position.all()
        departments=Department.all()
        
        data['managers']=managers
        data['positions']=positions
        data['departments']=departments
        
        thilux_util.render_page(self.response, html_page, data)
        
class AddPosition(webapp.RequestHandler):
    def get(self, q):
        html_page=('ADD_POSITION_PAGE')
        
        thilux_util.render_page(self.response, html_page)
        
class AddPositionAction(webapp.RequestHandler):
    def post(self):
        request = self.request
        
        position_name = request.get('positionname')
        position_description=request.get('positiondescription')
        
        position=Position()
        position.name=position_name
        position.description=position_description
        
        position.put()
        
        success_message='Position added successfully!'
        
        html_page=('ADD_POSITION_PAGE')
        
        data={'success_message': success_message}
        
        thilux_util.render_page(self.response, html_page, data)    
        
class AddDepartment(webapp.RequestHandler):
    def get(self,q):
        html_page=('ADD_DEPARTMENT_PAGE')
        
        thilux_util.render_page(self.response, html_page)
        
class AddDepartmentAction(webapp.RequestHandler):
    def post(self):
        
        html_page=('ADD_DEPARTMENT_PAGE')
        
        request=self.request
        department_name=request.get('departmentname')
        
        data={}
        
        department=Department.get_by_key_name(department_name)
        
        if department:
            errors=('Department %s already exists!' % department_name, )
            data['errors']=errors
        else:
            department=Department(key_name=department_name)
            department.put()
            
            success_message='Department has been created successfully!'
            
            data['success_message']=success_message
        
        thilux_util.render_page(self.response, html_page, data)

class SignIn(webapp.RequestHandler):
    def post(self):

        request = self.request
        login = request.get('login')
        password = str(request.get('password'))
        
        user = User.get_by_key_name(login)
        
        html_page = ('INDEX_PAGE')
        
        data = {}
        
        if not user:
            '''No user found! Throw error'''
            errors = ('Username or password are incorrect!',)
            data = {'errors' : errors, }
            thilux_util.render_page(self.response, html_page, data)
            return
        else:
            '''There is a user, validate password and status'''
            if user.status == _STATUS_ACTIVE:
                if user.password == thilux_security.encrypt(password):
                    '''Let it in'''
                else:
                    '''Password is wrong'''
                    errors = ('Username or password are incorrect!',)
                    data = {'errors' : errors, }
                    thilux_util.render_page(self.response, html_page, data)
                    return
            else:
                '''User is not active'''
                errors = ('Username or password are incorrect!',)
                data = {'errors' : errors, }
                thilux_util.render_page(self.response, html_page, data)
                return
            
        thilux_session.create_session_for_user(user)
        
        html_page = ('DOOR1')
        # data={'menus': gen_menu_for_user(), }
        
        thilux_util.render_page(self.response, html_page, data)

class MainPage(webapp.RequestHandler):
    def get(self, q):
        
        html_page = ''
        data = {}
        
        if thilux_session.is_user_logged():
            html_page = ('DOOR1')

        else:
            html_page = ('INDEX_PAGE')
        
        '''path = os.path.join(os.path.dirname(__file__), html_page)
        
        self.response.out.write(template.render(path, {}))'''
        thilux_util.render_page(self.response, html_page, data)

class MainPageTest(webapp.RequestHandler):
    def get(self, q):
        # html_page=('INDEX_PAGE')
        html_page = ('INDEX_TEST_PAGE')
        
        '''path = os.path.join(os.path.dirname(__file__), html_page)
        
        self.response.out.write(template.render(path, {}))'''
        thilux_util.render_page(self.response, html_page)
        
class UsersPage(webapp.RequestHandler):
    def get(self, q):
        
        html_page = ('USERS_PAGE')
        
        users = User.all()
        # menus = gen_menu_for_user()
        
        data = {'users': users, }
        
        thilux_util.render_page(self.response, html_page, data)
        
class AddUserPage(webapp.RequestHandler):
    def get(self, q):
        
        html_page = ('ADD_USER_PAGE')
        roles_k = Role.all(keys_only=True)
        roles = [role.name() for role in roles_k]
        
        data = {'roles' : roles, }
        
        thilux_util.render_page(self.response, html_page, data)
        
class LogOut(webapp.RequestHandler):
    def get(self, q):
        
        thilux_session.terminate_session()
            
        html_page = ('INDEX_PAGE')
        
        thilux_util.render_page(self.response, html_page)
            
        
class AddUserAction(webapp.RequestHandler):
    def post(self):
        
        request = self.request
        login = request.get('login')
        
        logging.info('Request content is %s' % str(request))
        
        user = User(key_name=login)
        
        user.first_name = request.get('firstName')
        user.last_name = request.get('lastName')
        
        role_name = str(request.get('roles'))
        role = Role.get_by_key_name(role_name)
        
        user.role = role
              
        user.birth_date = datetime.strptime(request.get('birthDate'), '%d/%m/%Y').date()
        
        # user.login=request.get('login')
        user.password = thilux_security.encrypt(str(request.get('password')))
        user.status = _STATUS_ACTIVE

        user.put()
        
        errors = ()
        
        data = {
               'errors' : errors,
               'success_message' : 'User has been created successfully',
               'user' : user,
               }
        
        html_page = ('ADD_USER_PAGE')
        
        thilux_util.render_page(self.response, html_page, data)
        
